import React, { useEffect, useState } from 'react';
import { RelationGraph } from '../components/RelationGraph';
import { SearchFilter, FilterOptions } from '../components/SearchFilter';
import { HerbList } from '../components/HerbList';
import { HerbDetail } from '../components/HerbDetail';
import './Home.css';

interface HomeProps {
  onHerbSelect?: (herbId: string) => void;
}

export const Home: React.FC<HomeProps> = ({ onHerbSelect }) => {
  const [allHerbs, setAllHerbs] = useState<any[]>([]);
  const [filteredHerbs, setFilteredHerbs] = useState<any[]>([]);
  const [relations, setRelations] = useState<any[]>([]);
  const [selectedHerb, setSelectedHerb] = useState<any>(null);
  const [relatedHerbs, setRelatedHerbs] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState<'list' | 'graph'>('list');
  const [isLoading, setIsLoading] = useState<boolean>(true);

  // 加载数据
  useEffect(() => {
    const loadData = async () => {
      try {
        setIsLoading(true);
        
        // 加载药材数据
        const herbsResponse = await fetch('/src/data/herbs.json');
        const herbsData = await herbsResponse.json();
        const herbs = Object.values(herbsData);
        setAllHerbs(herbs);
        setFilteredHerbs(herbs);
        
        // 加载关系数据
        const relationsResponse = await fetch('/src/data/relations.csv');
        const relationsText = await relationsResponse.text();
        const relationsList = relationsText.split('\n')
          .slice(1) // 跳过标题行
          .filter(line => line.trim() !== '')
          .map(line => {
            const [source, target, type, strength] = line.split(',');
            return { source, target, type, strength: parseFloat(strength) };
          });
        setRelations(relationsList);
        
        setIsLoading(false);
      } catch (error) {
        console.error('Failed to load data:', error);
        setIsLoading(false);
      }
    };

    loadData();
  }, []);

  // 当选择药材时，查找相关药材
  useEffect(() => {
    if (!selectedHerb || !relations.length) return;
    
    const findRelatedHerbs = () => {
      const relatedIds = relations
        .filter(rel => rel.source === selectedHerb.id || rel.target === selectedHerb.id)
        .map(rel => {
          const otherId = rel.source === selectedHerb.id ? rel.target : rel.source;
          return {
            herbId: otherId,
            relation: {
              type: rel.type,
              strength: rel.strength
            }
          };
        });
      
      const herbsWithRelations = relatedIds.map(item => {
        const herb = allHerbs.find(h => h.id === item.herbId);
        return {
          herb,
          relation: item.relation
        };
      }).filter(item => item.herb !== undefined);
      
      setRelatedHerbs(herbsWithRelations);
    };
    
    findRelatedHerbs();
  }, [selectedHerb, relations, allHerbs]);

  // 处理搜索筛选
  const handleSearch = (filters: FilterOptions) => {
    let filtered = [...allHerbs];
    
    // 关键词筛选
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase();
      filtered = filtered.filter(herb => 
        herb.name.toLowerCase().includes(keyword) || 
        herb.description?.toLowerCase().includes(keyword) ||
        herb.functions.some((f: string) => f.toLowerCase().includes(keyword))
      );
    }
    
    // 分类筛选
    if (filters.categories.length > 0) {
      filtered = filtered.filter(herb => 
        filters.categories.includes(herb.category)
      );
    }
    
    // 药性筛选
    if (filters.properties.性.length > 0) {
      filtered = filtered.filter(herb => 
        filters.properties.性.includes(herb.properties.性)
      );
    }
    
    // 药味筛选
    if (filters.properties.味.length > 0) {
      filtered = filtered.filter(herb => 
        herb.properties.味.some((w: string) => filters.properties.味.includes(w))
      );
    }
    
    // 功效筛选
    if (filters.functions.length > 0) {
      filtered = filtered.filter(herb => 
        filters.functions.some(func => herb.functions.includes(func))
      );
    }
    
    setFilteredHerbs(filtered);
  };

  // 处理药材点击
  const handleHerbClick = (herbId: string) => {
    const herb = allHerbs.find(h => h.id === herbId);
    setSelectedHerb(herb);
    
    // 如果提供了 onHerbSelect 回调，则调用它
    if (onHerbSelect) {
      onHerbSelect(herbId);
    }
  };

  // 处理相关药材点击
  const handleRelatedHerbClick = (herbId: string) => {
    handleHerbClick(herbId);
  };

  // 处理关系图中节点点击
  const handleNodeClick = (node: any) => {
    // 如果节点没有完整数据，通过ID从allHerbs中获取完整的药材数据
    if (node && node.id) {
      const completeHerb = allHerbs.find(h => h.id === node.id);
      if (completeHerb) {
        setSelectedHerb(completeHerb);
        
        // 如果提供了 onHerbSelect 回调，则调用它
        if (onHerbSelect) {
          onHerbSelect(node.id);
        }
        
        // 在移动设备上，点击关系图节点后自动滚动到详情区域
        if (window.innerWidth <= 1200) {
          setTimeout(() => {
            document.querySelector('.right-panel')?.scrollIntoView({ behavior: 'smooth' });
          }, 100);
        }
      } else {
        setSelectedHerb(node); // 备选方案：如果找不到完整数据，仍然使用节点数据
      }
    } else {
      setSelectedHerb(node);
    }
  };

  if (isLoading) {
    return (
      <div className="loading">
        <div className="loading-spinner"></div>
        <p>正在加载本草纲目数据...</p>
      </div>
    );
  }

  return (
    <div className="home-container">
      <header className="app-header">
        <h1>本草纲目数据可视化系统</h1>
      </header>

      <main className="main-content">
        <div className="left-panel">
          <SearchFilter onSearch={handleSearch} />
          
          <div className="tab-navigation">
            <button 
              className={`tab-btn ${activeTab === 'list' ? 'active' : ''}`} 
              onClick={() => setActiveTab('list')}
            >
              列表视图
            </button>
            <button 
              className={`tab-btn ${activeTab === 'graph' ? 'active' : ''}`} 
              onClick={() => setActiveTab('graph')}
            >
              关系图谱
            </button>
          </div>
          
          <div className="tab-content">
            {activeTab === 'list' ? (
              <div className="list-view fade-in">
                <HerbList 
                  herbs={filteredHerbs} 
                  onHerbClick={handleHerbClick}
                />
              </div>
            ) : (
              <div className={`graph-view fade-in ${selectedHerb ? 'active-graph' : ''}`}>
                <RelationGraph
                  onNodeClick={handleNodeClick}
                />
              </div>
            )}
          </div>
        </div>
        
        <div className="right-panel">
          {selectedHerb && (
            <HerbDetail 
              herb={selectedHerb} 
              relatedHerbs={relatedHerbs}
              onRelatedHerbClick={handleRelatedHerbClick}
              onClose={() => setSelectedHerb(null)}
            />
          )}
        </div>
      </main>
    </div>
  );
}; 